<template>
  <div class="transport-container">
    <div class="search-section animate__animated animate__fadeInDown">
      <el-input style="width: 200px;margin-right: 20px" placeholder="请输入订单ID" v-model="orderId" prefix-icon="el-icon-document"></el-input>
      <el-input style="width: 200px;margin-right: 20px" placeholder="请输入车辆ID" v-model="vehicleId" prefix-icon="el-icon-truck"></el-input>
      <el-button style="margin-left: 10px;" type="primary" @click="search" class="el-icon-search">搜索</el-button>
      <el-button style="margin-left: 10px;" type="warning" @click="reset" class="el-icon-refresh">重置</el-button>
      <el-button style="margin-left: 10px;" type="success" @click="showAddDialog" class="el-icon-plus">添加运输记录</el-button>
    </div>

    <div class="table-section animate__animated animate__fadeInUp">
      <el-table
          :data="tableData" border stripe
          :header-cell-style="getRowClass"
          @selection-change="handleSelectionChange"
          row-key="transportId">
        
        <el-table-column prop="transportId" label="运输ID"></el-table-column>
        <el-table-column prop="orderId" label="订单ID"></el-table-column>
        <el-table-column prop="vehicleId" label="车辆ID"></el-table-column>
        <el-table-column prop="startLocation" label="起始地"></el-table-column>
        <el-table-column prop="endLocation" label="目的地"></el-table-column>
        <el-table-column prop="currentTemp" label="当前温度">
          <template slot-scope="scope">
            <div style="display: flex; align-items: center;">
              <span :style="{ color: getTemperatureColor(scope.row.currentTemp) }">
                {{ scope.row.currentTemp }}°C
              </span>
              <el-button 
                size="mini" 
                type="info" 
                icon="el-icon-warning" 
                circle 
                style="margin-left: 10px;" 
                @click="checkTemperature(scope.row)"
                :title="'检查温度是否在产品安全范围内'"
              ></el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <div class="operation-buttons">
              <el-button size="mini" type="primary" class="el-icon-edit" @click="handleUpdateTemp(scope.row)">更新温度</el-button>
              <el-button size="mini" type="success" class="el-icon-check" @click="handleComplete(scope.row)" v-if="scope.row.status === '1'">完成运输</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="block" style="padding:10px 0;align-content: center;margin-left: 30%;margin-top:30px;">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </div>

    <el-dialog title="添加运输记录" :visible.sync="addDialogVisible" width="30%">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="订单ID" prop="orderId">
          <el-input v-model="form.orderId"></el-input>
        </el-form-item>
        <el-form-item label="车辆ID" prop="vehicleId">
          <el-input v-model="form.vehicleId"></el-input>
        </el-form-item>
        <el-form-item label="起始地" prop="startLocation">
          <el-input v-model="form.startLocation"></el-input>
        </el-form-item>
        <el-form-item label="目的地" prop="endLocation">
          <el-input v-model="form.endLocation"></el-input>
        </el-form-item>
        <el-form-item label="初始温度" prop="currentTemp">
          <el-input-number v-model="form.currentTemp" :min="-50" :max="50"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAdd">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="更新温度" :visible.sync="tempDialogVisible" width="30%">
      <el-form :model="tempForm" :rules="tempRules" ref="tempForm" label-width="100px">
        <el-form-item label="运输ID" prop="transportId">
          <el-input v-model="tempForm.transportId" disabled></el-input>
        </el-form-item>
        <el-form-item label="当前温度" prop="currentTemp">
          <el-input-number v-model="tempForm.currentTemp" :min="-50" :max="50"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="tempDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleTempSave">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 温度检查结果对话框 -->
    <el-dialog title="温度检查结果" :visible.sync="tempCheckDialogVisible" width="40%">
      <div v-if="tempCheckResult">
        <el-alert
          :title="tempCheckResult.message"
          :type="tempCheckResult.status === '正常' ? 'success' : 'error'"
          :description="tempCheckResult.status === '正常' ? '所有产品温度均在安全范围内' : '存在产品温度超出安全范围'"
          show-icon
          :closable="false"
          style="margin-bottom: 20px;"
        ></el-alert>
        
        <div v-if="tempCheckResult.details && Object.keys(tempCheckResult.details).length > 0">
          <h4>详细检查结果：</h4>
          <el-table :data="formatTempCheckDetails(tempCheckResult.details)" border>
            <el-table-column prop="productId" label="产品ID" width="180"></el-table-column>
            <el-table-column prop="status" label="温度状态">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status ? 'success' : 'danger'">
                  {{ scope.row.status ? '正常' : '异常' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="tempCheckDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import 'animate.css/animate.min.css';

export default {
  name: "TransportDetails",
  data() {
    return {
      pageSize: 10,
      pageNum: 1,
      orderId: '',
      vehicleId: '',
      tableData: [],
      addDialogVisible: false,
      tempDialogVisible: false,
      tempCheckDialogVisible: false, // 温度检查结果对话框
      tempCheckResult: null, // 温度检查结果
      form: {
        orderId: '',
        vehicleId: '',
        startLocation: '',
        endLocation: '',
        currentTemp: 0,
        status: '1'
      },
      tempForm: {
        transportId: '',
        currentTemp: 0
      },
      multipleSelection: [],
      total: 0,
      rules: {
        orderId: [
          { required: true, message: '请输入订单ID', trigger: 'blur' }
        ],
        vehicleId: [
          { required: true, message: '请输入车辆ID', trigger: 'blur' }
        ],
        startLocation: [
          { required: true, message: '请输入起始地', trigger: 'blur' }
        ],
        endLocation: [
          { required: true, message: '请输入目的地', trigger: 'blur' }
        ],
        currentTemp: [
          { required: true, message: '请输入温度', trigger: 'blur' }
        ]
      },
      tempRules: {
        currentTemp: [
          { required: true, message: '请输入温度', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.load();
  },
  methods: {
    load() {
      this.request.get("/transport/findAll").then(res => {
        if (res.code === '200') {
          let data = res.data;
          // 根据搜索条件过滤
          if (this.orderId) {
            data = data.filter(item => item.orderId.includes(this.orderId));
          }
          if (this.vehicleId) {
            data = data.filter(item => item.vehicleId.includes(this.vehicleId));
          }
          this.tableData = data;
          this.total = data.length;
        }
      });
    },
    getRowClass({rowIndex, columnIndex}) {
      if(rowIndex === 0) {
        return 'background:#ccc'
      }
    },
    reset() {
      this.orderId = '';
      this.vehicleId = '';
      this.load();
    },
    search() {
      this.load();
    },
    showAddDialog() {
      this.form = {
        orderId: '',
        vehicleId: '',
        startLocation: '',
        endLocation: '',
        currentTemp: 0,
        status: '1'
      };
      this.addDialogVisible = true;
    },
    handleAdd() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.request.post("/transport/save", this.form).then(res => {
            if (res.code === '200') {
              this.$message.success('添加成功');
              this.addDialogVisible = false;
              this.load();
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
    handleUpdateTemp(row) {
      this.tempForm = {
        transportId: row.transportId,
        currentTemp: row.currentTemp
      };
      this.tempDialogVisible = true;
    },
    handleTempSave() {
      this.$refs.tempForm.validate((valid) => {
        if (valid) {
          this.request.put("/transport/updateTemperature/" + this.tempForm.transportId, {
            currentTemp: this.tempForm.currentTemp
          }).then(res => {
            if (res.code === '200') {
              this.$message.success('温度更新成功');
              this.tempDialogVisible = false;
              this.load();
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
    handleComplete(row) {
      this.$confirm('确认完成运输?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.put("/transport/updateStatus/" + row.transportId, {
          status: '2'
        }).then(res => {
          if (res.code === '200') {
            this.$message.success('运输完成');
            this.load();
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
    // 检查温度是否在产品安全范围内
    checkTemperature(row) {
      const orderId = row.orderId;
      if (!orderId) {
        this.$message.error('订单ID不能为空');
        return;
      }
      
      this.request.get(`/transport/checkTemperature/${orderId}`).then(res => {
        if (res.code === '200') {
          this.tempCheckResult = res.data;
          this.tempCheckDialogVisible = true;
        } else {
          this.$message.error(res.msg || '检查温度失败');
        }
      }).catch(err => {
        this.$message.error('检查温度请求失败: ' + (err.message || err));
      });
    },
    // 格式化温度检查详情为表格数据
    formatTempCheckDetails(details) {
      if (!details) return [];
      
      return Object.entries(details).map(([productId, status]) => {
        return {
          productId,
          status
        };
      });
    },
    getTemperatureColor(temp) {
      if (temp > 30) return '#F56C6C';
      if (temp < 0) return '#409EFF';
      return '#67C23A';
    },
    getStatusType(status) {
      switch (status) {
        case '1': return 'primary';
        case '2': return 'success';
        default: return 'info';
      }
    },
    getStatusText(status) {
      switch (status) {
        case '1': return '运输中';
        case '2': return '已完成';
        default: return '未知';
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.load();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.load();
    }
  }
}
</script>

<style scoped>
.transport-container {
  padding: 20px;
}

.search-section {
  margin-bottom: 20px;
}

.table-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.operation-buttons {
  display: flex;
  gap: 5px;
}

.el-button {
  margin: 0;
}

.el-table {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}
</style> 